package com.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.common.constant.AuthServerConstant;
import com.common.exception.BizCodeEnume;
import com.common.utils.R;
import com.common.vo.MemberRespVo;
import com.gulimall.auth.vo.UserLoginVo;
import com.gulimall.auth.vo.UserRegistVo;
import com.gulimall.auth.feign.MemberFeignService;
import com.gulimall.auth.feign.ThirdPartFeignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class LoginController {

    @Autowired
    ThirdPartFeignService thirdPartFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    MemberFeignService memberFeignService;

    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone){
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (!StringUtils.isEmpty(redisCode)) {
            if (System.currentTimeMillis() - Long.parseLong(redisCode.split("_")[1]) < 60000) {
                //在60秒内
                return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(), BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
            }
        }
        String code = String.valueOf((int)((Math.random() * 9 + 1) * 1000));
        //redis缓存验证码，防止同一个手机在60秒再次发送验证码
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone,code+"_"+System.currentTimeMillis(),20, TimeUnit.MINUTES);
        thirdPartFeignService.sendCode(phone,code);
        return R.ok();
    }

    @GetMapping("/login.html")
    public String loginPage(HttpSession session){
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (attribute == null){
            return "login";
        }else {
           return  "redirect:http://gulimall.com";
        }

    }


    @PostMapping("login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession httpSession){
        R r = memberFeignService.login(vo);
        if (r.getCode() == 0){
            MemberRespVo data = r.getData("data", new TypeReference<MemberRespVo>() {
            });
            httpSession.setAttribute(AuthServerConstant.LOGIN_USER,data);
            return "redirect:http://gulimall.com";
        }else {
            HashMap<String, String> map = new HashMap<>();
            map.put("msg",r.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors",map);
            return "redirect:http://auth.gulimall.com/login.html";
        }

    }


    @PostMapping("/regist")
    public String regist(@Valid UserRegistVo registVo, BindingResult result, RedirectAttributes redirectAttributes){
        if (result.hasErrors()){
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors",errors);

            return "redirect:http://auth.gulimall.com/reg.html";
        }
        //1、校验验证码
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + registVo.getPhone());
        if (!StringUtils.isEmpty(redisCode)){
            if (redisCode.split("_")[0].equals(registVo.getCode())){
                //验证码通过
                // 1、删除验证码
                redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + registVo.getPhone());
                // 2、调远远程服务
                R r = memberFeignService.regist(registVo);
                if (r.getCode() == 0){
                    //成功
                    return "redirect:http://auth.gulimall.com/login.html";
                }else {
                    //失败
                    HashMap<String, String> hashMap = new HashMap<>();
                    hashMap.put("data",r.getData("msg",new TypeReference<String>(){}));
                    redirectAttributes.addFlashAttribute("errors",hashMap);
                   return  "redirect:http://auth.gulimall.com/reg.html";
                }

            }else {
                //验证码失效
                HashMap<String, String> map = new HashMap<>();
                map.put("code","验证码错误");
                redirectAttributes.addFlashAttribute("errors",map);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        }else {
            //验证码失效
            HashMap<String, String> map = new HashMap<>();
            map.put("code","验证码错误");
            redirectAttributes.addFlashAttribute("errors",map);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
    }

/*    @GetMapping("/login.html")
    public String loginPage(){
        return "login";
    }


    @GetMapping("/reg.html")
    public String regPage(){
        return "reg";
    }*/
}
